﻿#if UNITY_IOS
using System.Runtime.InteropServices;
#endif
using System.IO;
using UnityEngine;

namespace BToolkit
{
    public class SavePhotoToAlbum
    {
        public enum UserAction { None, Disable, DisableForever }

        /// <summary>
        /// Android判断是否有存储权限
        /// </summary>
        public static bool HaveAndroidSavePermission()
        {
            if (!Application.isEditor && Application.platform == RuntimePlatform.Android)
            {
                return AndroidUtils.CallAndroidStaticFunction<bool>("cn.btoolkit.savephoto.SavePhotoToAlbum", "havaSavePermission");
            }
            return true;
        }

        /// <summary>
        /// Android请求存储权限
        /// </summary>
        public static UserAction RequestSavePermission()
        {
            if (!Application.isEditor && Application.platform == RuntimePlatform.Android)
            {
                int action = AndroidUtils.CallAndroidStaticFunction<int>("cn.btoolkit.savephoto.SavePhotoToAlbum", "requestSavePermission");
                if(action == 1)
                {
                    return UserAction.Disable;
                }else if (action == 2)
                {
                    return UserAction.DisableForever;
                }
            }
            return UserAction.None;
        }


        /// <summary>
        /// 保存到相册，Android需指定文件名并会自动刷新相册，iOS无需指定文件名
        /// </summary>
        public static void Save(byte[] bytes, string androidFileName = null)
        {
            if (Application.isEditor)
            {
                File.WriteAllBytes(Application.persistentDataPath + "/" + androidFileName, bytes);
            }
            else if (Application.platform == RuntimePlatform.Android)
            {
                //手机存储卡根目录
                string saveFullPath = "/storage/emulated/0/DCIM/" + androidFileName;
                AndroidUtils.CallAndroidStaticFunction("cn.btoolkit.savephoto.SavePhotoToAlbum", "save", bytes, saveFullPath);
            }
            else if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
#if UNITY_IOS
                _SaveImgToPhotosAlbum(bytes, bytes.Length);
#endif
            }
        }


        /// <summary>
        /// Andriod新保存到相册的照片需要刷新相册后才能显示（Save()方法会自动刷新）
        /// </summary>
        public static void AndroidRefreshAlbum(string fileFullPath)
        {
            AndroidUtils.CallAndroidStaticFunction("cn.btoolkit.savephoto.SavePhotoToAlbum", "refreshAlbum", fileFullPath);
        }

#if UNITY_IOS
        [DllImport("__Internal")]
        static extern void _SaveImgToPhotosAlbum(byte[] bytes, int bytesLength);
#endif

    }
}